<?php

/*
 *用户相关的类
 *
 *
 */

namespace app\common\controller;

use app\common\model\User as UserModel;
use fast\Random;
use think\Controller;
use think\Validate;
use think\Cookie;
use think\Session;
use think\Db;

/**
 * Description of User
 *
 * @author Administrator
 */
class Users extends Controller
{
    //put your code here
    public $errormsg = '';

    public function login($data)
    {
        $rule = [
            'mobile' => ['/^1[34578]\d{9}$/'],
            'password' => 'require|length:6,30',

        ];
        $msg = [
            'mobile' => '手机号输入有误',
            'password.require' => '密码不能为空',
            'password.length' => '密码要 6 到 30 个字符',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->errormsg = $validate->getError();
            return false;
        }
        $user = UserModel::get(['mobile' => $data['mobile']]);
        if (!$user || $user->password != $this->getEncryptPassword($data['password'], $user->salt)) {
            $this->errormsg = '用户名或密码错误';
            return false;
        }

        if ($user->status != 'normal') {
            $this->errormsg = '用户被封号';
            return false;
        }
        $expire = 10 * 86400;
        Cookie::set('uid', $user->id, $expire);
        return $user;
    }

    public function register($data)
    {
        $rule = [
            'mobile' => ['/^1[34578]\d{9}$/'],
            'password' => 'require|length:6,30',
            'infoCode' => 'require|length:4',
        ];
        $msg = [
            'mobile' => '手机号输入有误',
            'password.require' => '密码不能为空',
            'password.length' => '密码要 6 到 30 个字符',
            'infoCode.require' => '短信验证码不能为空',
            'infoCode.length' => '短信验证码长度四位',
        ];
        //验证数据
        /*$validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result)
        {
            $this->errormsg= $validate->getError();
            return false;
        }*/

        $time = time();
        //短信验证
        /*
        if (!Session::has($data['mobile'])){
            $this->errormsg = "请首先接收验证码";
            return false;
        }
         $sess = json_decode(Session::pulldata['mobile']));

         if ($sess['sms'] != $data['infoCode'] || $time-$data['time']>60){
             $this->errormsg = "验证码错误或过期";
             return false;
         }*/
        $is_register = "select id from rwz_user where mobile = " . $data['mobile'];
        $is_register = Db::query($is_register);
        if ($is_register) {
            $this->errormsg = '手机号已绑定，请登录';
            return false;
        }
        $ip = request()->ip();
        $salt = Random::alnum();

        $data = [
            'password' => $data['password'],
            'mobile' => $data['mobile'],
            'level' => 1,
            'score' => 0,
            'avatar' => '',
        ];
        $salt = Random::alnum();
        $params = array_merge($data, [
            'salt' => $salt,
            'jointime' => $time,
            'joinip' => $ip,
            'logintime' => $time,
            'loginip' => $ip,
            'prevtime' => $time,
            'status' => 'normal'
        ]);
        $params['password'] = $this->getEncryptPassword($data['password'], $params['salt']);
        $user = UserModel::create($params);
        if ($user->id) {
            $expire = 10 * 86400;
            Cookie::set('uid', $user->id, $expire);
            return $user;
        } else {
            $this->errormsg = '注册失败！请重试';
            return false;
        }
    }


    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public function sendSms($mobile)
    {
        $rule = [
            'mobile' => ['/^1[34578]\d{9}$/'],
        ];
        $msg = [
            'mobile' => '手机号输入有误',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check(['mobile' => $mobile]);
        if (!$result) {
            $this->errormsg = $validate->getError();
            return false;
        }
        $user = User::get(['mobile' => $mobile]);
        if (!empty($user)) {
            $this->errormsg = '用户已存在';
            return false;
        }
        $sms = rand(1000, 9999) . '';
        $res = json_decode(send_sms($sms, $mobile), true);
        if ($res['code'] == '000000') {
            $data['sms'] = $sms;
            $data['time'] = strtotime($res['create_date']);
            Session::set($mobile, json_encode($data));
            return true;
        } else {
            return false;
        }
    }

    public function getUserInfo($uid)
    {
        if (!empty($uid)) {
            $sql = 'select nickname,email,mobile,avatar,gender,birthday,user_money,qq,city_id from rwz_user where id = ' . $uid;
            $res = Db::query($sql);
            if ($res) {
                $user_info = $res[0];
                return $user_info;
            }
        }
        return false;
    }

    public function perfectInfo($data, $uid)
    {
        $info = $this->getUserInfo($uid);
        $perfect['nickname'] = isset_empty($data['nickname']) ? $data['nickname'] : $info['mobile'];
        $perfect['gender'] = isset_empty($data['gender']) ? $data['gender'] : 0;
        $perfect['birthday'] = isset_empty($data['birthday']) ? $data['birthday'] : date('Y-m-d');
        $perfect['city_id'] = isset_empty($data['area']) ? $data['area'] : "110100";
        $perfect['qq'] = isset_empty($data['qq']) ? $data['qq'] : "110100";
        //完善信息没有选择头像的功能，先使用系统默认头像
        $perfect['avatar'] = "/assets/img/avatar.png";
        //进行用户的更新
        $res = db('user')->where('id', $uid)->update($perfect);
        if ($res || $res == 0) {
            return true;
        } else {
            $this->errormsg = "未知错误，完善信息失败";
            return false;
        }
    }
    public function heardUpdate($uid)
    {
        $file = request()->file('image');
        if (empty($file)) {
            $this->errormsg='上传文件为空';
            return false;
        }
        //移动到框架应用根目录/public/uploads/ 目录下
        $path =  DS . 'uploads';
        $info = $file->validate(['size'=>65536,'ext'=>'jpg,png,gif'])->move($path);
        if ($info) {
            $path = $path. DS .$info->getSaveName();
            $data['avatar'] = $path;
            $res = db('user')->where('id', $uid)->update($data);
            if ($res || $res == 0) {
                return $path;
            } else {
                $this->errormsg = "未知错误，完善信息失败";
                return false;
            }
        } else {
            //上传失败获取错误信息
            $this->errormsg = $file->getError();
            return false;
        }
    }
}
